# -*- coding: utf-8 -*-
# @Date    : 2015-06-21 15:50:35
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

from lib.tornado_routes import route
from web.handler import BaseHandler
from tornado import gen
from tornado.web import asynchronous
from web.models.admin.user.student import Student
from web.models.admin.repair.device import Device
import json
import time
import base64
from lib import libupload
from lib.app import libtype


@route(r'/admin/repair/device/?')
class DeviceListHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self):
        cur_page = self.get_argument('page', default=1)
        school_id = self.get_argument('schoolId', default=self.school_id)

        school = self.get_cookie('school', base64.b16encode('{}'))
        school = json.loads(base64.b16decode(school))
        dt = school.get('device', {})
        device_name = dt.get('device_name', '')
        device_dorm = dt.get('device_dorm', '')
        device_room = dt.get('device_room', '')
        device_type = dt.get('device_type', '')
        where = {
            "Fname":   device_name,
            "Fdorm_id": device_dorm,
            "Froom_id":   device_room,
            "Ftype_id": device_type,
        }

        page = (int(cur_page) - 1) * self.offset

        room = []
        # device_type = yield Device().select_device_type(school_id)
        drom = yield Student().select_dorm(school_id)
        if device_dorm != '':
            room = yield Student().select_room(school_id, device_dorm)
        ret, count = yield Device().select_device(school_id, where, page, self.offset)

        page_info = {'total': count, 'page': int(cur_page)}
        type_list = libtype.get_type_dict()
        # self.render("admin/repair/device/list.html", data=ret, room=room,
        #             page_info=page_info, drom=drom, where=where, device_type=device_type)
        self.render("admin/repair/device/list.html", data=ret, room=room,
                    page_info=page_info, drom=drom, where=where, type_list = type_list)

    def post(self):
        cur_page = self.get_argument('page', default='1')
        school_id = self.get_argument('schoolId', default=self.school_id)
        device_name = self.get_argument('Fname', default='')
        device_dorm = self.get_argument('Fdorm_id', default='')
        device_room = self.get_argument('Froom_id', default='-1')
        device_type = self.get_argument('Ftype_id', default='-1')

        school = self.get_cookie('school', base64.b16encode('{}'))
        school = json.loads(base64.b16decode(school))
        dt = school.get('device', {})

        if device_name != '':
            dt["device_name"] = device_name
        else:
            dt.pop('device_name', '')

        if device_dorm != '':
            dt["device_dorm"] = device_dorm
        else:
            dt.pop('device_dorm', '')

        if device_room != '-1':
            dt["device_room"] = device_room
        else:
            dt.pop('device_room', '')

        if device_type != '-1':
            dt["device_type"] = device_type
        else:
            dt.pop('device_type', '')

        school["device"] = dt
        self.set_cookie('school', base64.b16encode(json.dumps(school)))

        self.redirect('/admin/repair/device/')


@route(r'/admin/repair/device/new/?')
class NewHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self):
        school_id = self.get_argument('schoolId', default=self.school_id)

        room = []
        # type_list = libtype.get_type_dict()
        # device_type = yield Device().select_device_type(school_id)
        device_type = libtype.get_type_dict()
        drom = yield Student().select_dorm(school_id)
        if len(drom) >= 1:
            room = yield Student().select_room(school_id, drom[0]["Fid"])

        self.render("admin/repair/device/new.html", drom=drom,
                    room=room, device_type=device_type)

    @asynchronous
    @gen.coroutine
    def post(self):
        ltype = self.get_argument('ltype', default='0')
        school_id = self.get_argument('schoolId', default=self.school_id)
        Fname = self.get_argument('Fname', default='')
        Fcode = self.get_argument('Fcode', default='')
        Ftype_id = self.get_argument('Ftype_id', default='')
        Fdorm_id = self.get_argument('Fdorm_id', default='')
        Froom_id = self.get_argument('Froom_id', default='')
        Fqrcode = self.get_argument('Fqrcode', default='')
        Fimg = self.request.files.get('Fimg')

        if Fimg is not None:
            Fimg, path = libupload.save(Fimg[0])
            libupload.img.thumbnail(path, path, 100, 100)
        else:
            Fimg = ""

        device_info_data = {
            "Ftype_id":         Ftype_id,
            "Froom_id":           Froom_id,
            "Fdorm_id":      Fdorm_id,
            "Fcode":         Fcode,
            "Fname":          Fname,
            "Fqrcode":          Fqrcode,
            "Fschool_id":    school_id,
            "Fimg":       Fimg,
            "Fcreate_time":  time.time()
        }

        count = yield Device().insert_device(device_info_data)

        if ltype == '0':
            self.redirect('/admin/repair/device/')
        else:
            self.redirect('/admin/repair/device/new/')


@route(r'/admin/repair/device/edit/(?P<Fid>[0-9].*)', name='device.edit')
class EditHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, Fid):
        school_id = self.get_argument('schoolId', default=self.school_id)

        device = yield Device().find_device(Fid)
        room = []
        # device_type = yield Device().select_device_type(school_id)
        device_type = device['Ftype_id']
        type_list = libtype.get_type_dict()

        drom = yield Student().select_dorm(school_id)
        if len(drom) >= 1:
            room = yield Student().select_room(school_id, drom[0]["Fid"])

        self.render(
            "admin/repair/device/edit.html", drom=drom, room=room, device_type=device_type, device=device, type_list=type_list)

    @asynchronous
    @gen.coroutine
    def post(self, Fid):
        school_id = self.get_argument('schoolId', default=self.school_id)
        Fname = self.get_argument('Fname', default='')
        Fcode = self.get_argument('Fcode', default='')
        Ftype_id = self.get_argument('Ftype_id', default='')
        Fdorm_id = self.get_argument('Fdorm_id', default='')
        Froom_id = self.get_argument('Froom_id', default='')
        Fqrcode = self.get_argument('Fqrcode', default='')
        Fimg = self.request.files.get('Fimg')

        if Fimg is not None:
            Fimg, path = libupload.save(Fimg[0])
            libupload.img.thumbnail(path, path, 100, 100)
        else:
            Fimg = ""

        device_info_data = {
            "Ftype_id":         Ftype_id,
            "Froom_id":           Froom_id,
            "Fdorm_id":      Fdorm_id,
            "Fcode":         Fcode,
            "Fname":          Fname,
            "Fqrcode":          Fqrcode,
            "Fschool_id":    school_id,
        }
        if Fimg != "":
            device_info_data['Fimg'] = Fimg

        count = yield Device().update_device(Fid, device_info_data)

        self.redirect('/admin/repair/device/')


@route(r'/admin/repair/device/del/(?P<FdeviceId>[0-9].*)/(?P<cur_page>[0-9].*)', name='device.del_device')
class DelHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, FdeviceId, cur_page):
        school_id = self.get_argument('schoolId', default=self.school_id)

        ret = Device().del_device(FdeviceId)

        self.redirect('/admin/repair/device/?page=' + cur_page)
